package com.example.solrdemo.dao;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

@Component
public final class HighlightMapper {

    private ObjectMapper objectMapper;

    public HighlightMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    //将结果高亮字段合并到对象
    public <T> void map(HighlightPage<T> page) {
        page.forEach(v ->{
            List<HighlightEntry.Highlight> highlights = page.getHighlights(v);
            highlights.forEach(highlight -> {
                String fName = highlight.getField().getName();
                try {
                    assert fName != null;
                    Field field = v.getClass().getDeclaredField(fName);
                    field.setAccessible(true);
                    Class<?> type = field.getType();
                    Object o = objectMapper.readValue(highlight.getSnipplets().get(0), type);
                    field.set(v,o);
                } catch (NoSuchFieldException | IOException | IllegalAccessException ignore) {
                }
            });
        });
    }
}
